/**
 * FileName: ValidatedExceptionHandler
 * Author:   liuws
 * Date:     2022/5/15 21:10
 */
package cn.edu.nhic.nhcarsb.exception;


import cn.edu.nhic.nhcarsb.entity.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice
public class GlobleExceptionHandler {
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public R error(RuntimeException e){
        e.printStackTrace();
        return R.error(e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R bindExceptionHandler(BindException e){
        BindingResult result = e.getBindingResult();
        String msg="";
        if(result.hasErrors()){
            for(FieldError error : result.getFieldErrors()){
                msg=msg+error.getDefaultMessage()+"<br/>";
            }
        }
        return R.error(msg);
    }
}
